package com.deer.wms.ASN.manage.web;

import com.deer.wms.ASN.manage.model.asn.AsnDetail;
import com.deer.wms.ASN.manage.model.asn.AsnDetailCriteria;
import com.deer.wms.ASN.manage.model.asn.AsnDetailDto;
import com.deer.wms.ASN.manage.model.asn.AsnMaster;
import com.deer.wms.ASN.manage.service.AsnDetailService;
import com.deer.wms.ASN.manage.service.AsnMasterService;
import com.deer.wms.intercept.annotation.Authority;
import com.deer.wms.intercept.annotation.User;
import com.deer.wms.intercept.common.data.CurrentUser;
import com.deer.wms.inventory.model.Inventory.Inventory;
import com.deer.wms.inventory.model.Inventory.ItemBatch;
import com.deer.wms.ASN.manage.model.upper.UpperTask;
import com.deer.wms.ASN.manage.model.upper.UpperTaskCriteria;
import com.deer.wms.ASN.manage.model.upper.UpperTaskInsert;
import com.deer.wms.inventory.service.ItemBatchService;
import com.deer.wms.ASN.manage.service.UpperTaskService;
import com.deer.wms.project.root.core.result.CommonCode;
import com.deer.wms.project.root.core.result.Result;
import com.deer.wms.project.root.core.result.ResultGenerator;
import com.deer.wms.project.root.util.DateUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.util.List;

/**
 * Created by guo on 2019/12/19.
 */
@Api(description = "上架api接口")
@RestController
@RequestMapping("/upper/tasks")
public class UpperTaskController {

    @Autowired
    private UpperTaskService upperTaskService;

    @Autowired
    private AsnMasterService asnMasterService;

    @Autowired
    private AsnDetailService asnDetailService;

    @Autowired
    private ItemBatchService itemBatchService;

    @PostMapping("/insert")
    public Result add(@RequestBody UpperTask upperTask) {
        upperTaskService.save(upperTask);
        return ResultGenerator.genSuccessResult();
    }

    @GetMapping("/delete")
    public Result delete(Integer id) {
        upperTaskService.removeById(id);
        return ResultGenerator.genSuccessResult();
    }

    @PostMapping("/update")
    public Result update(@RequestBody UpperTask upperTask) {
        upperTaskService.updateById(upperTask);
        return ResultGenerator.genSuccessResult();
    }

    @GetMapping("/detail")
    public Result detail(@PathVariable Integer id) {
        UpperTask upperTask = upperTaskService.getById(id);
        return ResultGenerator.genSuccessResult(upperTask);
    }

    @GetMapping("/list")
    public Result list(UpperTaskCriteria criteria) {
        PageHelper.startPage(criteria.getPageNum(), criteria.getPageSize());
        List<UpperTask> list = upperTaskService.findList(criteria);
        PageInfo pageInfo = new PageInfo(list);
        return ResultGenerator.genSuccessResult(pageInfo);
    }


    @ApiOperation(value = "查询合适的货位", notes = "查询合适的货位")
    @GetMapping("/findUpperCell")
    public Result findUpperCell(Inventory inventory) {
        String cellCode = upperTaskService.findUpperCell(inventory);
        return ResultGenerator.genSuccessResult(cellCode);
    }

    @ApiOperation(value = "上架", notes = "上架")
    @Authority
    @ApiImplicitParams({@ApiImplicitParam(name = "access-token", value = "token", paramType = "header", dataType = "String", dataTypeClass = String.class,  required = true)})
    @PostMapping("/upperTask")
    public Result upperTask(@RequestBody UpperTaskInsert upperTaskInsert, @ApiIgnore @User CurrentUser currentUser) {
        if (currentUser == null) {
            return ResultGenerator.genFailResult(CommonCode.MISSING_PERMISSION_PARAMTER, null);
        }
        Integer userId = currentUser.getUserId();
        String userName = currentUser.getUserName();
        String createTime = DateUtils.getNowDateTimeString();

        upperTaskInsert.setUpperTaskUserId(userId);
        upperTaskInsert.setUpperTaskUserName(userName);
        upperTaskInsert.setCreateTime(createTime);
        upperTaskService.upperTask(upperTaskInsert);

        ItemBatch itemBatch = itemBatchService.getById(upperTaskInsert.getBatchId());
        String detailNo = itemBatch.getDetailNo();
        if (!detailNo.equals("")) {
            AsnDetail asnDetail = asnDetailService.findBy("detail_no", detailNo);
            asnDetail.setUpperQuantity(upperTaskInsert.getToQuantity() + asnDetail.getUpperQuantity());
            asnDetailService.updateById(asnDetail);
            //上架以后更新detail的状态
            if (asnDetail.getUpperQuantity().equals(asnDetail.getAcceptQuantity())) {
                // 没执行
                asnDetail.setState(4);//已完成
            }
            asnDetailService.updateById(asnDetail);
            //根据detail的条数判断 master的asn收货状态
            AsnDetailCriteria criteria = new AsnDetailCriteria();
            criteria.setBillNo(asnDetail.getBillNo());
            List<AsnDetailDto> asnDetails = asnDetailService.findList(criteria);
            AsnMaster asnMaster = asnMasterService.findBy("bill_no", asnDetail.getBillNo());
            for (int i = 0; i < asnDetails.size(); i++) {
                Integer state = asnDetails.get(i).getState();
                if (state == 4) {
                    asnMaster.setAsnState(4);
                }
            }
            asnMasterService.updateById(asnMaster);
        }

        return ResultGenerator.genSuccessResult();
    }

    @ApiOperation(value = "生成上架任务", notes = "生成上架任务")
    @PostMapping("/generateInCellTask")
    public Result generateInCellTask(@RequestBody List<Inventory> inventories) {
        upperTaskService.generateInCellTask(inventories);
        return ResultGenerator.genSuccessResult();
    }
}
